package com.tr.rentcar.common.filter;

import java.io.IOException;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class LoginFilter
 * 登录过滤器
 */
@WebFilter(dispatcherTypes = {
				DispatcherType.REQUEST, 
				DispatcherType.FORWARD
		}
					, urlPatterns = { "/*" })
public class LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req= (HttpServletRequest) request;
		HttpServletResponse resp=(HttpServletResponse) response;
		HttpSession session = req.getSession();
		
		String path = req.getServletPath();
		//找不到用户信息才过滤
		if(session.getAttribute("userinfo")==null){
			if("/goods/order".equals(path)||path.startsWith("/user")||"/orderok".equals(path)){
				String url=req.getRequestURL()+"?"+ req.getQueryString();
				//System.out.println("地址："+req.getRequestURL()+"?"+ req.getQueryString());
				session.setAttribute("goUrl", url);
				resp.sendRedirect(req.getContextPath()+"/login");
				return;
			}else if("/ddiscount".equals(path)&& req.getHeader("x-requested-with")!=null && "XMLHttpRequest".equalsIgnoreCase(req.getHeader("x-requested-with"))){
				//过滤指定的ajax请求
				session.setAttribute("goUrl", req.getContextPath()+"/huodong");
				//想http头添加状态
				resp.setHeader("sessionstatus", "timeout");
				resp.setStatus(403);
				//添加登录的url
				resp.addHeader("loginpath", req.getContextPath()+"/login");
			}
		}
		if(session.getAttribute("admininfo")==null){
			if("/houtaiview".equals(path)){
				resp.sendRedirect(req.getContextPath()+"/houtaiadminlogin");
				return;
			}
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
